package multithreading;

public class Demo11_ATM {

    public static void main(String[] args) throws InterruptedException {

        Account acc = new Account(200);

        Thread a = new Thread(new A(acc,100));
        Thread b = new Thread(new B(acc,50));

        a.start();
        b.start();
        a.join();
        b.join();

        System.out.println(acc.money);
    }

}

class Account{

    double money;

    public Account(double money) {
        this.money = money;
    }

    public synchronized void saveMoney(double money) throws InterruptedException {
        Thread.sleep(2000);
        System.out.println("账户当前有"+this.money+"元钱");
        this.money += money;
    }

    public synchronized void takeMoney(double money) throws InterruptedException {
        Thread.sleep(2000);
        System.out.println("账户当前有"+this.money+"元钱");
        this.money -= money;
    }
}

class A implements Runnable{

    Account acc;

    double money;

    public A(Account acc, double money) {
        this.acc = acc;
        this.money = money;
    }

    @Override
    public void run() {
        try {
            acc.saveMoney(this.money);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }
}


class B implements Runnable{
    Account acc;

    double money;

    public B(Account acc, double money) {
        this.acc = acc;
        this.money = money;
    }

    @Override
    public void run() {
        try {
            acc.takeMoney(this.money);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }
}